package com.example.pan.ui.file

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.example.pan.http.PanService
import com.example.pan.model.FileInfo

class DriveFileDataSource(
    private val service: PanService,
    private val dir: String,
    private val token: String,
) : PagingSource<Int, FileInfo>() {

    override fun getRefreshKey(state: PagingState<Int, FileInfo>): Int? {
        return state.anchorPosition
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, FileInfo> {
        return try {
            val start = params.key ?: 0
            val response = service.list(token, dir, "time", "0", start, params.loadSize)
            if (response.errno == 0) {
                val nextKey = if (response.list.isEmpty()) null else start + params.loadSize
                LoadResult.Page(response.list, null, nextKey)
            } else {
                LoadResult.Error(Throwable(response.errno.toString()))
            }
        } catch (e: Exception) {
            e.printStackTrace()
            LoadResult.Error(e)
        }
    }
}